// pages/message/message.js
let template = require('./../../template/tabbar.js');
import { queryRecommendNotRead, querySystemNotRead, queryHouseNotRead } from "../../service/msg_service"

import { queryOnlineCustomer } from "../../service/config"
// imTODO
import { queryIMConversationList, cancelConversationRequest } from "../../service/newIm_service"
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    themeStyle: "",
    navBarTitle: "消息中心",
    conversationList: [],
    notReadNumber: 0,//系统消息未读数量
    scrollRefreshStatus: true,
    recommendNotRead: 0,//报备未读数量
    houseNotRead: 0,//楼盘未读数量
    systemNotRead: 0,//系统未读数量
    shareNotRead: 0,//共享未读消息数量
    isLogin: false,
    totalNotReadNum: 0,
    onlineCustomer: {},// 客服号
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    // template.tabbar("tabBar", 3, this, 0, app.globalData.roleType)//0表示第一个tabbar
    let that = this;
    // wx.hideTabBar();
    //监听到会话列表变化了:
    app.conversationChangeWatch(that.conversationChangeWatchBack);
    this.setData({
      isLogin: app.globalData.isLogin
    })
    this.queryOnlineCustomer();
  },
  handleContact() {
    try {
      wx.openCustomerServiceChat({
        extInfo: {
          url: 'https://work.weixin.qq.com/kfid/kfcb2e4e40e00f7c68b' //客服ID
        },
        corpId: '', //企业微信ID
        success(res) { },
        fail: err => {
          console.error("JJLog:失败原因:", err);
        }
      })
    } catch (error) {
      showToast("请更新至微信最新版本")
    }
    // wx.navigateTo({
    //   url: '/firstPackage/pages/chatWebPage/chatWebPage',
    // })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.themeStyle) {
      this.setData({
        themeStyle: app.globalData.themeStyle
      })
    }
    this.setData({
      totalNotReadNum: 0,
    })
    // this.getConversationList();
    // imTODO
    // this.getNewConversationList();
    // this.queryRecommendNotRead();
    // this.querySystemNotRead();
    // this.queryHouseNotRead();
   
  },


  //监听到
  conversationChangeWatchBack: function (newConItem) {
    //  console.log("JJLog:最新的会话列表项是:" + JSON.stringify(newConItem));
    // this.getConversationList();
    // imTODO
    // this.getNewConversationList();
  },
  // imTODO 获取新的会话列表:
  getNewConversationList() {
    queryIMConversationList().then(res => {
      console.log("JJLog:获取新的会话列表:" + JSON.stringify(res));
      if (res.code == 200) {
        let conversationList = res.data;
        this.setData({
          conversationList,
          scrollRefreshStatus: false
        })
        let unreadCount = 0
        conversationList.forEach((item, index) => {
          unreadCount = unreadCount + item.notRead
        })
        app.globalData.conversationList = conversationList;
        setTimeout(() => {
          app.globalData.unreadCount = unreadCount + this.data.totalNotReadNum;

          // template.tabbar("tabBar", 3, this, app.globalData.unreadCount, app.globalData.roleType)//0表示第一个tabbar

        }, 1000);
      }
    }).catch(err => {
      console.error("JJLog:获取会话列表失败:", err);
      this.setData({
        scrollRefreshStatus: false
      })
    })
  },
  queryOnlineCustomer() {
    queryOnlineCustomer().then(res => {
      console.log("JJLog:获取到的客服是:" + JSON.stringify(res));
      if (res.code == 200) {
        if (res.data) {
          this.setData({
            onlineCustomer: res.data
          })

        }
      }
    }).catch(err => {
      this.setData({
        onlineCustomer: {},
      })
    })
  },
  //获取当前的会话列表:
  getConversationList() {
    let promise = app.globalData.tim.getConversationList();
    promise.then(imResponse => {
      console.log("JJLog:获取到的会话列表是:" + JSON.stringify(imResponse));
      let conversationList = imResponse.data.conversationList;

      this.setData({
        conversationList,
        scrollRefreshStatus: false
      })
      let unreadCount = 0
      conversationList.forEach((item, index) => {
        unreadCount = unreadCount + item.unreadCount
      })
      setTimeout(() => {
        app.globalData.unreadCount = unreadCount + this.data.totalNotReadNum;
        // template.tabbar("tabBar", 3, this, app.globalData.unreadCount, app.globalData.roleType)//0表示第一个tabbar
      }, 1000);

      // console.log("JJLog:未读数量是:" + app.globalData.unreadCount);

      app.globalData.conversationList = conversationList;
    }).catch(imError => {
      this.setData({
        scrollRefreshStatus: false
      })
      console.warn('JJLog获取会话列表失败:', imError); // 获取会话列表失败的相关信息
    });
  },
  //跳转到聊天界面
  pushToChat(e) {
    let item = e.currentTarget.dataset.item;
    let chatData = {
      name: item.nick,
      avatar: item.avatar,
      chatUserId: item.userID,
      conversationType: "C2C",
    }
    app.globalData.chatData = chatData;
    //chatType:0默认单聊，1就是群聊
    wx.navigateTo({
      url: "/firstPackage/pages/msgModule/chatRoom/chatRoom"
    })
  },

  // 跳转客服
  serviceAction() {
    let item = this.data.onlineCustomer
    let name = "";
    if (item.realName) {
      name = item.realName;
    } else {
      name = item.nickName
    }
    let chatData = {
      name: name,
      avatar: item.avatar,
      chatUserId: item.openId,
      conversationType: "C2C",

    }
    app.globalData.chatData = chatData;
    wx.navigateTo({
      url: '/firstPackage/pages/msgModule/chatRoom/chatRoom',
    })
  },

  //跳转到对应的消息列表
  sysMsgAction(e) {
    let type = e.currentTarget.dataset.type;
    if (!app.globalData.isLogin) {
      wx.navigateTo({
        url: '/pages/login/login',
      })
      return;
    }
    if (type == "sys") {
      wx.navigateTo({
        url: '/firstPackage/pages/msgModule/sysMsgList/sysMsgList',
      })
    } else if (type == "house") {
      wx.navigateTo({
        url: '/firstPackage/pages/msgModule/houseMsgList/houseMsgList',
      })
    } else if (type == "recommend") {
      wx.navigateTo({
        url: '/firstPackage/pages/msgModule/recommendMsgList/recommendMsgList',
      })
    } else if (type == "customer") {
      wx.navigateTo({
        url: '/firstPackage/pages/customManager/customList/customList',
      })
    } else {
      wx.navigateTo({
        url: '/formPackage/pages/shareTeamList/shareTeamList',
      })
    }

  },
  //删除会话列表:
  closeCell(e) {
    let index = e.currentTarget.dataset.index;
    console.log("JJLog:当前点击的会话列表是:" + index);
    let conList = this.data.conversationList;
    let converItem = this.data.conversationList[index];
    let conversationID = converItem.conversationID;
    wx.showLoading();
    let promise = app.globalData.tim.deleteConversation(conversationID);
    promise.then(imResponse => {
      wx.hideLoading();
      console.log("JJLog:删除会话列表成功:" + JSON.stringify(imResponse));
      conList.splice(index, 1);
      this.setData({
        conversationList: conList
      })
    }).catch(imError => {
      wx.hideLoading();
      wx.showToast({
        title: '操作失败',
        icon: "none"
      })
      console.error("JJLog:closeCell:", imError);
    });
    // console.log("JJLog:当前要删除的会话是:" + JSON.stringify(converItem));
  },

  //删除一条会话记录:
  cancelOneCon(e) {
    let index = e.currentTarget.dataset.index;
    wx.showModal({
      title: '提示',
      content: '删除当前会话,会清空当前会话聊天记录',
      success: res => {
        if (res.confirm) {
          this.cancelConRequest(index);
        }
      }
    })

  },
  cancelConRequest(index) {
    let conList = this.data.conversationList;
    let converItem = this.data.conversationList[index];
    let conversationId = converItem.conversationId;
    wx.showLoading();
    cancelConversationRequest({ conversationId: conversationId }).then(res => {
      wx.hideLoading();
      if (res.code == 200) {
        conList.splice(index, 1);
        this.setData({
          conversationList: conList
        })
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: '操作失败',
        icon: "none"
      })
      console.error("JJLog:删除会话列表失败:", err);
    })

    // let promise = app.globalData.tim.deleteConversation(conversationID);
    // promise.then(imResponse => {
    //   wx.hideLoading();
    //   console.log("JJLog:删除会话列表成功:" + JSON.stringify(imResponse));
    //   conList.splice(index, 1);
    //   this.setData({
    //     conversationList: conList
    //   })
    // }).catch(imError => {
    //   wx.hideLoading();
    //   wx.showToast({
    //     title: '操作失败',
    //     icon: "none"
    //   })
    //   console.log("JJLog:删除会话列表失败:", imError);
    // });
  },

  //scrollView下拉刷新:
  refreshDownData() {
    this.setData({
      scrollRefreshStatus: true
    })
    // this.getConversationList();
    // this.querySystemNotRead();
    // this.queryRecommendNotRead();
    // this.queryHouseNotRead();
   
    // this.getNewConversationList();
  },


  //报备消息未读数量
  queryRecommendNotRead() {
    queryRecommendNotRead().then(res => {
      console.log("JJLog:报备未读数量:" + JSON.stringify(res));
      if (res.code == 200) {
        this.setData({
          recommendNotRead: res.data || 0
        })
        let num = res.data || 0;
        let totalNum = this.data.totalNotReadNum;
        if (num > 0) {
          totalNum = totalNum + num;
          this.setData({
            totalNotReadNum: totalNum,
          })
          // app.globalData.unreadCount = this.data.totalNotReadNumber;
          // template.tabbar("tabBar", 3, this, app.globalData.unreadCount)//0表示第一个tabbar
        }

      }
    }).catch(err => {
      wx.hideLoading();
      console.error("JJLog:queryRecommendNotRead", err);
    })
  },
  //系统消息未读数量
  querySystemNotRead() {
    querySystemNotRead().then(res => {
      console.log("JJLog:系统消息未读数量:" + JSON.stringify(res));
      if (res.code == 200) {
        this.setData({
          systemNotRead: res.data || 0
        })
        let num = res.data || 0;
        let totalNum = this.data.totalNotReadNum;
        if (num > 0) {
          totalNum = totalNum + num;
          this.setData({
            totalNotReadNum: totalNum,
          })
          // app.globalData.unreadCount = this.data.totalNotReadNumber;
          // template.tabbar("tabBar", 3, this, app.globalData.unreadCount)//0表示第一个tabbar
        }
      }
    }).catch(err => {
      wx.hideLoading();
      console.error("JJLog:querySystemNotRead", err);
    })
  },
  //楼盘未读消息数量
  queryHouseNotRead() {
    queryHouseNotRead().then(res => {
      console.log("JJLog:楼盘消息未读数量:" + JSON.stringify(res));
      if (res.code == 200) {
        this.setData({
          houseNotRead: res.data || 0
        })
        let num = res.data || 0;
        let totalNum = this.data.totalNotReadNum;
        if (num > 0) {
          totalNum = totalNum + num;
          this.setData({
            totalNotReadNum: totalNum,
          })
          // app.globalData.unreadCount = this.data.totalNotReadNumber;
          // template.tabbar("tabBar", 3, this, app.globalData.unreadCount)//0表示第一个tabbar
        }
      }
    }).catch(err => {
      wx.hideLoading();
      console.error("JJLog:queryHouseNotRead", err);
    })
  },








})